/*
 * $Id: RequestTrackingFilter.java 42 2013-04-17 15:33:59Z gabakyan $
 * $Author: gabakyan $
 * $Revision: 42 $
 * $Date: 2013-04-17 15:33:59 +0000 (Wed, 17 Apr 2013) $
 *
 * Copyright (c) 2013 Supply Chain Intelligence (SCI), Inc.
 * http://www.scintelligence.com/, Email: info@scintelligence.com
 * All rights reserved.
 *
 * This file is part of Logistics Map.
 *
 * Logistics Map is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * Logistics Map is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Logistics Map.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.sci.logisticsmap.web.support;

import com.sci.logisticsmap.service.support.GeoIPUtilities;
import com.sci.logisticsmap.service.support.GlobalBriefcase;
import com.sci.logisticsmap.service.support.RuntimeConfigurationInstance;
import com.sci.logisticsmap.service.support.SessionBriefcase;
import com.sci.logisticsmap.support.Constants;
import com.sci.logisticsmap.support.model.UserStatus;
import com.sci.logisticsmap.service.model.SessionUserDTModel;
import com.sci.logisticsmap.web.security.support.SecurityContextHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//import static com.sci.logisticsmap.web.controller.BaseController.PATH_AJAX;
import static com.sci.logisticsmap.web.controller.BaseController.PATH_RESOURCES;
import static com.sci.logisticsmap.web.controller.BaseController.PATH_ADMIN;

import static com.sci.logisticsmap.web.controller.MainController.PATH_HOME;

import static com.sci.logisticsmap.web.controller.MainController.PATH_ABOUT;
import static com.sci.logisticsmap.web.controller.MainController.PATH_PRIVACY;
import static com.sci.logisticsmap.web.controller.MainController.PATH_TERMS;

import static com.sci.logisticsmap.web.controller.MessageController.PATH_MESSAGE_BASE;

import static com.sci.logisticsmap.web.controller.MessageController.PATH_MESSAGE_LOCKED_DOWN;
import static com.sci.logisticsmap.web.controller.MessageController.PATH_MESSAGE_NOT_ALLOWED_COUNTRY;

import static com.sci.logisticsmap.web.controller.MessageController.PATH_MESSAGE_BLOCKED_USER;
import static com.sci.logisticsmap.web.controller.MessageController.PATH_MESSAGE_REJECTED_USER;
import static com.sci.logisticsmap.web.controller.MessageController.PATH_MESSAGE_UNAPPROVED_USER;

import static com.sci.logisticsmap.web.controller.SignInController.PATH_SIGN_OUT;

import static com.sci.logisticsmap.web.controller.SignUpController.PATH_SIGN_UP_CONFIRMATION;
import static com.sci.logisticsmap.web.controller.SignUpController.PATH_SIGN_UP_CONTINUE;
import static com.sci.logisticsmap.web.controller.SignUpController.PATH_SIGN_UP_SUCCESS;

/**
 * The class {@code RequestTrackingFilter} represents the once per request filter
 * which implements the servlet context listener.
 *
 * @author gabakyan@gmail.com (Last modified by $Author: gabakyan $)
 * @version $Revision: 42 $
 */
public class RequestTrackingFilter extends OncePerRequestFilter implements ServletContextListener {
    /**
     * The logger.
     */
    private static final Logger logger = LoggerFactory.getLogger(RequestTrackingFilter.class);
    /**
     * The GeoIP Utilities.
     */
    private static GeoIPUtilities geoIPUtilities;

    /**
     * The continue chain flag
     * which associates with current thread of execution.
     */
    private static final ThreadLocal<Boolean> continueChain = new ThreadLocal<Boolean>() {
        /*
         * (non-Javadoc)
         *
         * @see ThreadLocal#initialValue()
         */
        @Override
        protected Boolean initialValue() {
            return Boolean.FALSE;
        }
    };

    /*
     * (non-Javadoc)
     *
     * @see ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent sce) {
        //logger.debug("RequestTrackingFilter init called...");
        ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
        geoIPUtilities = applicationContext.getBean(GeoIPUtilities.class);
    }

    /*
     * (non-Javadoc)
     *
     * @see ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent sce) {
        SessionBriefcase.INSTANCE.clear();
    }

    /*
     * (non-Javadoc)
     *
     * @see OncePerRequestFilter#doFilterInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)
     */
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
        //logger.debug("RequestTrackingFilter doFilter called...");

        continueChain.set(Boolean.TRUE);

        String path = request.getRequestURI().substring(request.getContextPath().length());
        //logger.debug("\tpath = {}", path);

        if (!isAdminPath(path)) {
            if (!isIgnoredPath(path)) {
                if (isAllowedCountry(request)) {
                    HttpSession session = request.getSession();
                    //if (SecurityContextHelper.isAuthenticatedUser(session)) {
                    SessionUserDTModel sessionUser = SecurityContextHelper.getAuthenticatedUserDTModel(session);
                    if (sessionUser != null) {
                        String newUserStatus;
                        if ((newUserStatus = GlobalBriefcase.INSTANCE.getUserStatus(sessionUser.getUsername())) != null) {
                            sessionUser.setStatus(newUserStatus);
                            GlobalBriefcase.INSTANCE.removeUserStatus(sessionUser.getUsername());
                        }

                        boolean nonStaticPath = !isStaticPath(path);
                        //logger.debug("\tnon-static-path = {}", String.valueOf(nonStaticPath));

                        if (RuntimeConfigurationInstance.INSTANCE.isLockedDown()) {
                            if (!path.startsWith(PATH_MESSAGE_LOCKED_DOWN) && nonStaticPath) {
                                forwardRequest(request, response, PATH_MESSAGE_LOCKED_DOWN);
                            }
                        } else {
                            boolean checkMessagePath = false;
                            if (sessionUser.getStatus() != null) {
                                if (sessionUser.getStatus().equals(UserStatus.NEW)) {
                                     if (!(path.startsWith(PATH_SIGN_UP_SUCCESS) || path.startsWith(PATH_SIGN_UP_CONFIRMATION)) && nonStaticPath) {
                                         sendRedirect(request, response, PATH_SIGN_UP_SUCCESS);
                                     }
                                } else if (/*sessionUser.getStatus().equals(UserStatus.NEW) || */sessionUser.getStatus().equals(UserStatus.VERIFIED)) {
                                    if (RuntimeConfigurationInstance.INSTANCE.isApprovalOnlyMode()) {
                                        if (!path.startsWith(PATH_MESSAGE_UNAPPROVED_USER) && nonStaticPath) {
                                            forwardRequest(request, response, PATH_MESSAGE_UNAPPROVED_USER);
                                        }
                                    } else {
                                        checkMessagePath = true;
                                    }
                                } else if (sessionUser.getStatus().equals(UserStatus.APPROVED)) {
                                        checkMessagePath = true;
                                } else if (sessionUser.getStatus().equals(UserStatus.NEW_INCOMPLETE) || sessionUser.getStatus().equals(UserStatus.VERIFIED_INCOMPLETE)) {
                                     if (!path.startsWith(PATH_SIGN_UP_CONTINUE) && nonStaticPath) {
                                         sendRedirect(request, response, PATH_SIGN_UP_CONTINUE);
                                     }
                                } else if (sessionUser.getStatus().equals(UserStatus.REJECTED)) {
                                    if (!path.startsWith(PATH_MESSAGE_REJECTED_USER) && nonStaticPath) {
                                        forwardRequest(request, response, PATH_MESSAGE_REJECTED_USER);
                                    }
                                } else if (sessionUser.getStatus().equals(UserStatus.BLOCKED)) {
                                    if (!path.startsWith(PATH_MESSAGE_BLOCKED_USER) && nonStaticPath) {
                                        forwardRequest(request, response, PATH_MESSAGE_BLOCKED_USER);
                                    }
                                }
                            }

                            if (checkMessagePath && isMessagePath(path)) {
                                sendRedirect(request, response, PATH_HOME);
                            }
                        }
                    }
                } else {
                    forwardRequest(request, response, PATH_MESSAGE_NOT_ALLOWED_COUNTRY);
                }
            }
        }

        if (continueChain.get()) {
            chain.doFilter(request, response);
        }
    }

    /**
     * Checks the given path.
     *
     * @param path the given path.
     *
     * @return <code>true</code> if the path is the <code>admin</code> path, otherwise
     * <code>false</code>.
     */
    private boolean isAdminPath(String path) {
        return path.startsWith(PATH_ADMIN);
    }

    /**
     * Checks the given path.
     *
     * @param path the given path.
     *
     * @return <code>true</code> if the path is the <code>static</code> path, otherwise
     * <code>false</code>.
     */
    private boolean isStaticPath(String path) {
        return path.startsWith(PATH_ABOUT)
                || path.startsWith(PATH_PRIVACY)
                || path.startsWith(PATH_TERMS);
    }

    /**
     * Checks the given path.
     *
     * @param path the given path.
     *
     * @return <code>true</code> if the path is <code>message</code> path, otherwise
     * <code>false</code>.
     */
    private boolean isMessagePath(String path) {
        return path.startsWith(PATH_MESSAGE_BASE);
    }

    /**
     * Checks the given path.
     *
     * @param path the given path.
     *
     * @return <code>true</code> if the path should be ignored, otherwise
     * <code>false</code>.
     */
    private boolean isIgnoredPath(String path) {
        return /*path.startsWith(PATH_AJAX) || */path.startsWith(PATH_RESOURCES) || path.startsWith(PATH_SIGN_OUT);
    }

    /**
     * Checks the given request country.
     *
     * @param request the http servlet request.
     *
     * @return <code>true</code> if the request country is allowed, otherwise
     * <code>false</code>.
     */
    private boolean isAllowedCountry(HttpServletRequest request) {
        boolean result = true;
        String countryCode = null;
        String clientIpAddr = WebUtilities.getClientIpAddr(request);
        if (clientIpAddr != null) {
            if (clientIpAddr.indexOf('.') > -1) {
                countryCode = geoIPUtilities.getCountryCode(clientIpAddr);
            } else if (clientIpAddr.indexOf(':') > -1) {
                countryCode = geoIPUtilities.getCountryCodeV6(clientIpAddr);
            }

            if (countryCode != null && !countryCode.equals(Constants.COUNTRY_CODE_UNKNOWN)) {
                String[] allowedCountryCodes = RuntimeConfigurationInstance.INSTANCE.getAllowedCountryCodes();
                if (allowedCountryCodes != null) {
                    boolean found = false;
                    for (String allowedCountryCode : allowedCountryCodes) {
                        if (allowedCountryCode.equals(countryCode)) {
                            found = true;
                            break;
                        }
                    }
                    result = found;
                }
            }
        }
        //logger.debug("\tclientIpAddr = {}, countryCode = {}", clientIpAddr, countryCode);
        return result;
    }

    /**
     * Forwards the given request
     * and sets the continue chain flag to false.
     *
     * @see com.sci.logisticsmap.web.support.WebUtilities#forwardRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, String)
     */
    private void forwardRequest(HttpServletRequest request, HttpServletResponse response, String path)
            throws ServletException, IOException {
        WebUtilities.forwardRequest(request, response, path);
        continueChain.set(Boolean.FALSE);
    }

    /**
     * Redirects the given request
     * and sets the continue chain flag to false.
     *
     * @see com.sci.logisticsmap.web.support.WebUtilities#sendRedirect(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, String)
     */
    private void sendRedirect(HttpServletRequest request, HttpServletResponse response, String path)
            throws IOException {
        WebUtilities.sendRedirect(request, response, path);
        continueChain.set(Boolean.FALSE);
    }
}
